package com.leyou.cart.interceptor;

import com.leyou.common.auth.entity.UserHolder;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author syf
 * @version 1.0
 * @date 2019/08/17 10:55
 * @Description TODO:当前拦截器的作用
 *                      在进入处理器之前，获取到request域中的id，并存储起来，供处理器或者service使用
 */
public class UserInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userId = request.getHeader("USER_ID");
        if (StringUtils.isBlank(userId)){
            //登陆失效或登陆失败
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        UserHolder.setUserId(userId);
        return true;
    }


    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    UserHolder.removeUserId();

    }
}
